<template lang="pug">
  .cart-dialog
    el-dialog(
      title="购物车",
      :visible.sync="showModal",
      width="900px",
      :before-close="beforeCloseHandler")
      table(v-if="getCartList")
        colgroup
          col(class="choose-col")
          col(class="name-col")
          col(class="price-col")
          col(class="amount-col")
          col(class="total-col")
          col(class="operate-col")
        thead
          tr
            th.choose
            th.name 商品名称
            th.price 价格
            th.amount 数量
            th.total 总价
            th.operate 操作
        tbody
          tr(v-for="goods in getCartList", :key="goods.productid")
            td
              .choose
                el-checkbox-group(v-model="checkedGoods", @change="changeSelected")
                  el-checkbox(:key="goods.price", :label="goods.cartid")
            td
              .name.clearfix
                .thumb.fl
                  img(:src="goods.productimgs[0].thumburl")
                .name-table.fl.tal
                  .title.omit2 {{goods.name}}
            td
              .price ￥ {{goods.price}}
            td
              .num
                el-input-number(v-model="goods.num", size="small", :min="1", :max="goods.stock", @change="handleChange(goods)", label="请输入商品")
            td
              .subtotal ￥ {{Math.round(parseFloat(goods.num * goods.price)*100)/100}}
            td
              .operation
                el-button(type="danger", size="mini", icon="el-icon-delete", @click="deleteGoods(goods.cartid)")
        //- tfoot
        //-   tr
        //-     td
        //-       .choose.choose-all.tac
        //-         el-checkbox(:indeterminate="isIndeterminate", v-model="checkAll", @change="handleCheckAllChange") 全选
        //-     td
        //-       .delete-select(@click="deletSelected") 删除选中商品
        //-     td
        //-     td
        //-       .goods-count
        //-         p 已选择
        //-           strong.bold.red {{checkedGoods.length}}
        //-           |件商品
        //-         p 共计
        //-           strong.bold.gray {{checkedGoods.length}}
        //-           |件商品
        //-     td
        //-       .goods-total
        //-         p 应付总额：
        //-           span.red ￥
        //-           strong.bold.red {{totalPrice}}
        //-         p 应付总额不含运费
        //-     td
        //-       .checkout
        //-         el-button(type="success", @click="goCheckout") 提交订单

      .table-bar.pos-a(v-if="getCartList")
        .tr.choose.choose-all.tac
          el-checkbox(:indeterminate="isIndeterminate", v-model="checkAll", @change="handleCheckAllChange") 全选
        .tr.delete-select.hand(@click="deletSelected") 删除选中商品
        .tr.goods-name
        .tr.goods-count
          p 已选择
            strong.bold.red {{checkedGoods.length}}
            |件商品
          p 共计
            strong.bold.gray {{checkedGoods.length}}
            |件商品
        .tr.goods-total
          p 应付总额：
            span.red ￥
            strong.bold.red {{Number(totalPrice).toFixed(2) }}
          p 应付总额不含运费
        .tr.checkout
          el-button(type="success", @click="goCheckout") 提交订单
      .empty-cart.tac.pos-r(v-if="!getCartList")
        .tip-box.pos-center
          i.iconfont.icon-cart
          p 你的购物车空空如也
</template>
<script>
import { mapGetters } from 'vuex'
import modalMixin from '@/mixins/modal'
export default {
  name: 'cartModal',
  mixins: [modalMixin],
  data () {
    return {
      checkAll: true,
      isIndeterminate: true,
      checkedGoods: [],
      selectGoods: [],
      count: 1,
      totalPrice: 0
    }
  },
  mounted () {
    this.$vgo.on('cart:show', () => {
      this.openModal()
      this.$bar.finish()
    })
  },
  computed: {
    ...mapGetters(['cartList']),
    getCartList() {
      if(this.cartList) {
        return this.cartList.list
      }
    }
  },
  methods: {
    handleChange(val) {
      let num = 0
      let cartid

      this.getCartList.map(item => {
        num += item.num
        if(item.cartid == val.cartid) {
          cartid = item.cartid
        }
      })

      if(val.num == val.stock) {
        val.num = val.stock
        this.$vgo.tip('当前商品库存仅剩 ' + val.stock + ' 件, 无法添加更多了', 'warning')
      }
      this.$store.dispatch('updateCartGoodsNum', [cartid, val.num])

      this.calcTotalMoney()
    },
    calcTotalMoney(){
      this.totalPrice = 0
      let tempArr = []
      this.getCartList.map(g => {
        this.checkedGoods.map(item => {
          if(item == g.cartid) {
            tempArr.push(g)
          }
        })
      })
      tempArr.map(g => {
        this.totalPrice += Math.round(parseFloat(g.num  * g.price)*100)/100
      })
    },
    changeSelected(val) {
      this.calcTotalMoney()
      let checkedCount = val.length
      this.checkAll = checkedCount === this.getCartList.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.getCartList.length
    },
    handleCheckAllChange(val) {
      this.checkedGoods = []
      this.selectGoods = []
      if(val) {
        this.getCartList.map(item => {
          this.checkedGoods.push(item.cartid)
        })
      }
      this.calcTotalMoney()
      this.isIndeterminate = false
    },
    deleteGoods(id) {
      this.$vgo.open(() => {
        this.$store.dispatch('deleteCartGoods', id)
        this.checkedGoods.map((it, idx) => {
          if(it === id) {
            this.checkedGoods.splice(idx, 1)
          }
        })
      })
    },
    deletSelected(){
      if(this.checkedGoods.length <= 0) {
        this.$vgo.tip('未选择任何商品')
        return
      }

      this.$vgo.open(() => {
        this.checkedGoods.map((id, idx) => {
          this.$store.dispatch('deleteCartGoods', id)
        })
        this.calcTotalMoney()
        this.$vgo.tip('删除成功', 'success')
      })
    },
    goCheckout() {
      if(this.checkedGoods.length <= 0) {
        this.$vgo.tip('未选择任何商品')
        return
      }
      else {
        this.selectGoods = []
        this.checkedGoods.map(i => {
          this.getCartList.map(item => {
            if(i == item.cartid) {
              this.selectGoods.push(item)
            }
          })
        })
        this.$vgo.emit('checkout', {goods: this.selectGoods, money: this.totalPrice})
        this.closeModal()
      }
    },
    closeModal() {
      this.showModal = false
      this.totalPrice = 0 // 重置总价格
      this.isIndeterminate = true // 重置全选复选框状态
      this.checkedGoods = [] // 清空选中的商品
    }
  }
}
</script>
<style lang="stylus">
@import '../../../assets/styles/mixin.styl'
$gray-dark = #D3DCE6
.cart-dialog
  .el-dialog__body
    padding: 0
    height: 480px
    padding-bottom: 80px
    overflow-y: auto

  .table-bar
    display: table
    bottom: 0
    left: 0
    width: 100%
    height: 45px
    padding: 15px 0
    background-color: #f2f6fc
    z-index: 2
    .tr
      display: table-cell
      text-align: center
    .choose-col
      width: 100px
    .goods-name
      width: 150px
    .delete-select
      width: 120px
    .goods-count, .goods-total
      width: 180px
    .checkout
      width: 170px

  .empty-cart
    min-height: 300px
    line-height: 40px
    .tip-box
      pos-center()
      font-size: 24px
      color: $gray-dark
      i
        font-size: 50px
</style>
